package skills.jssvc.deu.cn.skillsecond.programming6;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.listener.ChartTouchListener;
import com.github.mikephil.charting.listener.OnChartGestureListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import skills.jssvc.deu.cn.skillsecond.MyApplication;
import skills.jssvc.deu.cn.skillsecond.R;
import skills.jssvc.deu.cn.skillsecond.util.SqlHelper;

public class RealDisplayFragment extends Fragment {
    private String TAG = "RealDisplayFragment";
    private View view;
    private TextView titleTv;
    private String[] titles ;
    private LineChart lineChart;
    private LineData lineData;
    private List<Entry> entryList;
    private LineDataSet lineDataSet;
    private TextView indexTv;
    private int[] indexTvs;
    private int index = 0;
    private SqlHelper helper;
    private SQLiteDatabase db;
    private List<String> xList;
    private OnChartGestureListener onChartGestureListener;
    private Timer timer;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_real_display, container, false);
        initView();
        initX();
        initData();
        return view;
    }

    private void initView(){
        titles = new String[]{"温度","湿度","PM2.5","CO2","光照","道路状态"};
        titleTv = (TextView) view.findViewById(R.id.frag6_real_title_tv);
        titleTv.setText(titles[index]);
        lineChart = (LineChart) view.findViewById(R.id.frag6_real_linchart);
        lineChart.setOnChartGestureListener(onChartListener());
        lineChart.setDoubleTapToZoomEnabled(false);
        lineChart.setScaleEnabled(false);
        lineChart.getLegend().setEnabled(false);
        lineChart.getDescription().setEnabled(false);
//      x轴
        XAxis xAxis = lineChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setAxisMinimum(0.5f);
        xAxis.setAxisMaximum(20f);
        xAxis.setLabelCount(20,false);
        xAxis.setLabelRotationAngle(90);
        xAxis.setDrawGridLines(false);
//      y轴
        lineChart.getAxisRight().setEnabled(false);
        lineChart.getAxisLeft().setDrawAxisLine(false);

        indexTvs = new int[]{R.id.frag6_real_index1_tv,R.id.frag6_real_index2_tv,R.id.frag6_real_index3_tv,
                R.id.frag6_real_index4_tv,R.id.frag6_real_index5_tv,R.id.frag6_real_index6_tv};
        indexTv = (TextView)view.findViewById(indexTvs[index]);
        indexTv.setBackgroundDrawable(getResources().getDrawable(R.drawable.cboder_2));

        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.sendMessage(new Message());
            }
        },10,3*1000);
    }

    private void initData(){
        entryList = new ArrayList<>();
//        switch (index){
//            case 0:
                for(int i=1;i<10;i++){
                    entryList.add(new Entry(i,(int)(Math.random()*10)));
                }
//                break;
//        }
        lineDataSet = new LineDataSet(entryList,"");
        lineDataSet.setDrawCircleHole(false);
        lineDataSet.setDrawValues(false);
        lineDataSet.setCircleColor(Color.rgb(170,170,170));
        lineDataSet.setColor(Color.rgb(170,170,170));
        lineData = new LineData(lineDataSet);
        lineChart.setData(lineData);
        lineChart.invalidate();
        indexTv = (TextView)view.findViewById(indexTvs[index]);
        indexTv.setBackgroundDrawable(getResources().getDrawable(R.drawable.cboder_2));
        titleTv.setText(titles[index]);
        Log.d(TAG, "initData: "+index);
    }

    private void initX(){
        xList = new ArrayList<>();
        helper = new SqlHelper(MyApplication.appContext, SqlHelper.DA_NAME, null, 1);
        db = helper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from " + SqlHelper.table_top,null );
        if(cursor.moveToFirst()){
            do {
                xList.add(cursor.getString(cursor.getColumnIndex("time")));
            } while (cursor.moveToNext());
        }

        XAxis xAxis = lineChart.getXAxis();
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float v, AxisBase axisBase) {
                if(v<xList.size()){
                    return xList.get((int) v);
                }else{
                    return "";
                }
            }
        });
        lineChart.invalidate();
    }

    private OnChartGestureListener onChartListener(){
        onChartGestureListener = new OnChartGestureListener() {
            @Override
            public void onChartFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
                if(v>0 && index<5){
                    index++;
                    indexTv.setBackgroundDrawable(getResources().getDrawable(R.drawable.cboder));
                    initX();
                    initData();
                }else if(v<0 && index>0){
                    index--;
                    indexTv.setBackgroundDrawable(getResources().getDrawable(R.drawable.cboder));
                    initX();
                    initData();
                }
                Log.d(TAG, "onChartFling: index="+index+"   v="+v);

            }

            @Override
            public void onChartGestureStart(MotionEvent motionEvent, ChartTouchListener.ChartGesture chartGesture) {

            }

            @Override
            public void onChartGestureEnd(MotionEvent motionEvent, ChartTouchListener.ChartGesture chartGesture) {

            }

            @Override
            public void onChartLongPressed(MotionEvent motionEvent) {

            }

            @Override
            public void onChartDoubleTapped(MotionEvent motionEvent) {

            }

            @Override
            public void onChartSingleTapped(MotionEvent motionEvent) {

            }

            @Override
            public void onChartScale(MotionEvent motionEvent, float v, float v1) {

            }

            @Override
            public void onChartTranslate(MotionEvent motionEvent, float v, float v1) {

            }
        };
        return onChartGestureListener;
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(isAdded()){
                initX();
                initData();
            }
        }
    };

}
